package net.piggy.file.utils;

import com.aspose.words.Document;
import com.aspose.words.SaveFormat;
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.concurrent.Future;

public class WordToPdfUtil {

    public static Boolean word2pdf(String path) {
        IConverter converter = LocalConverter.builder().build();
        String type = path.substring(path.lastIndexOf(".")+1);
        DocumentType documentType;
        if("doc".equals(type)){
            documentType = DocumentType.DOC;
        } else if ("docx".equals(type)) {
            documentType = DocumentType.DOCX;
        } else {
            throw new RuntimeException("type error");
        }
        try (InputStream inputStream = Files.newInputStream(Paths.get("D:\\chalk\\aaa.doc"));
             OutputStream outputStream = Files.newOutputStream(Paths.get("D:\\chalk\\bbb.pdf"))) {
            Future<Boolean> schedule = converter.convert(inputStream)
                    .as(documentType)
                    .to(outputStream)
                    .as(DocumentType.PDF)
                    .schedule();
            return schedule.get();
        } catch (Exception e) {
            e.printStackTrace();
            return Boolean.FALSE;
        }finally {
//            converter.kill();
            converter.shutDown();
        }
    }


    public static void word2pdf(String wordPath, String pdfPath) throws Exception {
        Document doc = new Document(wordPath);
        doc.save(pdfPath, SaveFormat.PDF);
    }

    public static void main(String[] args) throws Exception {
        word2pdf("D:\\chalk\\aaa.doc","D:\\chalk\\aaa.pdf");
    }
}
